// const { RoomUser, RoomChatHistory } = require('../mongoDB/schema.js')
// await new RoomChatHistory(data).save().then(res => {
//   console.log('添加到数据库成功');
// })

const WebSocket = require('ws')
let messages = 0
module.exports = (server) => {
  const socket = new WebSocket.Server(server)
  socket.on('connection', function connection(ws) {

    ws.on('message', function incoming(message) {
      console.log('received: %s', message);
      ws.send('接收传递的消息' + message);

      ws.a = message
      messages = message
      socket.broadcast(1)
    });
    ws.send('链接成功');

    ws.on('close', async function close(e) {
      socket.broadcast(2);
    });
  });


  // 广播
  socket.broadcast = function broadcast(type) {
    if (type === 1) {
      socket.clients.forEach(function each(client) {
        console.log(client.a, messages);
        if(client.a === messages) {
          client.send(JSON.stringify({
            data: 'welcome'
          }));
        }        
      });
    } else if (type === 2) {
      socket.clients.forEach(function each(client) {
        client.send(JSON.stringify({
          data: 'bye'
        }));
      });
    }

  };
}
